package com.atguigu.flink.tableapi;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Expressions;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * Created by Smexy on 2023/3/4
 *              streamAPI                      flinksql
 *  编程环境: StreamExectionEnviroment       StreamTableEnvironment
 *
 *  数据模型：DataStream                        Table(动态表)
 *
 */
public class Demo1_HelloWorld
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //创建编程环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<WaterSensor> ds = env
            .socketTextStream("hadoop103", 8888)
            .map(new WaterSensorMapFunction());

        //获取动态表
        Table table = tableEnv.fromDataStream(ds);

        //打印表的结构  参考流中POJO的属性
        table.printSchema();

        /*
            执行查询
            Expression: 查询表达式。
                            select 常量,列名(变量),函数

               使用 Expressions.xx() 构造Expression对象。
                例如:  Expressions.$(): 获取某一列
                        Expression.lit(): 构造常量
         */
        Table result = table.select($("id"), $("ts"), $("vc"))
                           .where($("id").isEqual("s1"));

        //直接用
        //result.execute().print();

        //把表转换为 DataStream，用之前的API操作
        DataStream<WaterSensor> ds2 = tableEnv.toDataStream(result, WaterSensor.class);

        ds2.print();



        try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }




    }
}
